﻿using System;
using System.Linq;
using NDBGen.Descriptors.Columns.Tokens;
using NDBGen.Descriptors.Tables.Tokens;
using NDBGen.Plugins.DataAccess;

namespace NDBGen.Plugins.Descriptors.Columns.Tokens
{
    [ColumnTokenCodeSnippetGenerator(typeof(ForeignKeyTokenDescriptor))]
    public sealed class DotNetForeignKeyTokenCodeGenerator : DotNetColumnTokenCodeGeneratorBase<ForeignKeyTokenDescriptor>
    {
        protected override Object[] GenerateCustomAttributes()
        {
            var fkTableKey = new TableKey(this.Descriptor.ForeignKeySchema, this.Descriptor.ForeignKeyTable);

            var fkTable = this.ParsedInput.Tables.SingleOrDefault(t => t.Key == fkTableKey);
            if(fkTable == null) throw new Exception(String.Format("Could not find the table referenced by the key {0}", fkTableKey));
            
            var referencesEnumTable = fkTable.Descriptors.Any(t => t.GetType() == typeof(EnumTokenDescriptor));

            if (referencesEnumTable) return ColumnMetadataHelper.NoCustomAttributes;
            else
            {
                return new Object[]
                {
                    String.Format(ColumnMetadataHelper.CustomAttributes.ForeignKeyForFormat,
                        String.Format("{0}.{1}", this.Descriptor.ForeignKeySchema.ToPascalCase(), this.Descriptor.ForeignKeyTable.Depluralize().ToPascalCase()),
                        this.Descriptor.ForeignKeyColumn.ToPascalCase())
                };
            }
        }
    }
}